<?php

namespace app\adminapi\controller;

use think\facade\Db;

class Jobclass extends Common
{
    public function list()
    {
        $data = $this->_vali([
            'keyword.default' => '',
            'doctimeStart.default' => '',
            'doctimeEnd.default' => '',
        ],"POST");

        $where = [];

        if ($data['keyword']) {
            $where[] = ['name','like',"%".$data['keyword']."%"];
        }

        $list = Db::name('jobclass')->field('id,name,sort,create_time,cover_img')->where($where)->paginate(10);

        $list = $list->toArray();

        foreach ($list['data'] as $key => $value) {
            $list['data'][$key]['create_time'] = date('Y-m-d H:i',$value['create_time']);
        }

        return json(['status'=>200,'sum'=>$list['total'],'list'=>$list['data']]);
    }


    /**
     * 添加/编辑
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save()
    {
        $data = $this->_vali([
            'id.default' => '',
            'name.require' => '请输分类名',
            'cover_img.require' => '请上传图片',
        ],"POST");

        if ($data['id']) {
            if (Db::name('jobclass')->where('id','<>',$data['id'])->where('name',$data['name'])->find()) {
                return json(['code'=>0,'msg'=>'角色名称已存在']);
            }
            $data['update_time'] = time();
            Db::name('jobclass')->where('id',$data['id'])->update($data);
        } else {
            if (Db::name('jobclass')->where('name',$data['name'])->find()) {
                return json(['status'=>0,'msg'=>'角色名称已存在']);
            }
            $data['create_time'] = time();
            if (Db::name('jobclass')->insert($data)) {
                return json(['status'=>200,'msg'=>'操作成功']);
            } else {
                return json(['status'=>0,'msg'=>'操作失败']);
            }
        }

        return json(['status'=>200,'msg'=>'操作成功']);
    }
}